package com.cremamobile.filemanager.fileWoker;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.cremamobile.filemanager.CremaActivity;
import com.cremamobile.filemanager.CremaWaitingProgressDialog;
import com.cremamobile.filemanager.R;
import com.cremamobile.filemanager.file.FileListEntry;
import com.cremamobile.filemanager.file.FileLister;
import com.cremamobile.filemanager.file.FileSorter;
import com.cremamobile.filemanager.file.NavigationEntry;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

public class Lister extends AsyncTask<FileListEntry, Integer, List<FileListEntry>>
{
	
	private CremaActivity caller;
	private CremaWaitingProgressDialog waitDialog;
	
	private FileListEntry currentFile;
	private FileSorter sorter;
	private boolean saveHistory;
	private int currentPosition;
	private boolean isRoot;
	
	public Lister(CremaActivity caller, FileSorter sorter, int currentPosition, boolean bHistory, boolean isRoot) {
		this.caller = caller;
		this.sorter = sorter;
		this.saveHistory = bHistory;
		this.currentPosition = currentPosition;
		this.isRoot = isRoot;
	}

	@Override
	protected void onPostExecute(List<FileListEntry> result) {

		if(waitDialog!=null && waitDialog.isShowing()) {
			waitDialog.dismiss();
		}
		
		List<FileListEntry> childFilesList = result;
		
		if (childFilesList == null)
			currentPosition = 0;
		else if (currentPosition >= childFilesList.size())
			currentPosition = childFilesList.size() -1;
		
		caller.setCurrentViewPerPath(currentFile, childFilesList, currentPosition, saveHistory, isRoot);	
	}
	
	@Override
	protected List<FileListEntry> doInBackground(FileListEntry... params) {
		Thread waitForASec = new Thread() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(100);
					if(this.isInterrupted()) {
						return;
					}
					else {
						caller.runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								waitDialog = CremaWaitingProgressDialog.show(caller, "", "", true, true, null);
							}
						});

					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				
			}
		};
		caller.runOnUiThread(waitForASec);
		
		currentFile = params[0];
		if (currentFile == null)
			return null;
		
		List<FileListEntry> files = FileLister.getFileLists(this.caller, currentFile, false, isRoot);
		Collections.sort(files, sorter);
		
		if(waitForASec.isAlive()) {
			try {
				waitForASec.interrupt();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return files;
	}
}
